$(function () {
    $(".navChoose").removeClass("navChoose");
    $("#introduce").addClass("navChoose");
    getNcFile();
    // gotoTop();
})

function fujianDowload() {
    var fileId = $("#fileId").val();
    var subClassName = $("#subClassName").val();
    window.location.href = cprefix + "/viewFile?fileid=" + fileId + "&subclassname=" + subClassName;
}

function getNcFile() {
    var productId = $("#productId").val();
    var tbody = $("#tbody");
    $.ajax({
        type: "post",
        async: true,
        url: ctx + "/getNcFile",
        data: {
            "productId": productId,
            "currentPage": 1
        },
        dataType: "json",        //返回数据形式为json
        success: function (data) {
            console.log(data)
            //debugger
            tbody.empty();
            var tmp = data.data
            result = tmp.map;
            for (var i = 0; i < result.length; i++) {
                tbody.append('<tr>');
                console.log("======================================================")
                if (result[i].unzip > 0) {
                    tbody.append('<td class="prt_tab_1"><a href="javascript:toUnzip(\'' + result[i].id + '\')">' + result[i].file_name + '</a></td>');
                } else {
                    tbody.append('<td class="prt_tab_1">' + result[i].file_name + '</td>');
                }
                var arr = [".pdf", ".docx", ".ppt", ".pptx", ".txt", ".xlsx", ".tar" ,".xls", ".doc", ".jpg", ".png", ".nc"];
                var a = arr.indexOf(getType(result[i].file_name));
                if ("-1" == a) {
                    tbody.append('<td class="prt_tab_1">' + result[i].file_size + 'MB</td>' +
                        '<td class="prt_tab_1">' + dateArrayTransfer(result[i].update_date) + '</td>' +
                        '<td class="prt_tab_2" width="180px"><a href="javascript:downLoad(\'' + result[i].id + '\',\''+result[i].file_name+'\',\''+result[i].product_id+'\')">下载</a>&nbsp;' +
                        '</td></tr>');
                } else {
                    console.log(result[i].toString())

                    tbody.append('<td class="prt_tab_1">' + result[i].file_size + 'MB</td>' +
                        '<td class="prt_tab_1">' + dateArrayTransfer(result[i].update_date) + '</td>' +
                        '<td class="prt_tab_2" width="180px"><a href="javascript:downLoad(\'' + result[i].id + '\',\''+result[i].file_name+'\',\''+result[i].product_id+'\')">下载</a>&nbsp;' +
                        '<a href="javascript:isPreview(\'' + result[i].product_id + ',' + result[i].id + ',' + result[i].file_name + ',' + dateArrayTransfer(result[i].update_date) + ',' + result[i].file_path + '\')">&nbsp;预览</a>' +
                        '</td></tr>');
                }
            }
            var pageCount = tmp.pageCount; //取到pageCount的值(把返回数据转成object类型)
            var currentPage = tmp.currentPage; //得到currentPage
            var options = {
                bootstrapMajorVersion: 3, //版本
                currentPage: currentPage, //当前页数
                totalPages: pageCount, //总页数
                shouldShowPage: false,
                itemTexts: function (type, page, current) {
                    switch (type) {
                        case "first":
                            return "首页";
                        case "prev":
                            return "上一页";
                        case "next":
                            return "下一页";
                        case "last":
                            return "末页";
                        case "page":
                            return page;
                    }
                },//点击事件，用于通过Ajax来刷新整个list列表
                onPageClicked: function (event, originalEvent, type, page) {
                    $.ajax({
                        url: ctx + "/getNcFile",
                        type: "post",
                        data: {
                            "productId": productId,
                            "currentPage": page
                        },
                        success: function (data) {
                            console.log(data)
                            var tmp = data.data
                            tbody.empty();
                            result = tmp.map;
                            for (var i = 0; i < result.length; i++) {
                                tbody.append('<tr>');
                                if (result[i].unzip > 0) {
                                    tbody.append('<td class="prt_tab_1"><a href="javascript:toUnzip(\'' + result[i].id + '\')">' + result[i].file_name + '</a></td>');
                                } else {
                                    tbody.append('<td class="prt_tab_1">' + result[i].file_name + '</td>');
                                }
                                tbody.append('<td class="prt_tab_1">' + result[i].file_size + 'MB</td>' +
                                    '<td class="prt_tab_1">' + dateArrayTransfer(result[i].update_date) + '</td>' +
                                    '<td class="prt_tab_2"><a href="javascript:downLoad(\'' + result[i].id + '\',\''+result[i].file_name+'\',\''+result[i].product_id+'\')">下载</a>&nbsp;&nbsp;');
                            }
                        }
                    });
                }
            };
            $('#example').bootstrapPaginator(options);
        }
    });
}

//判断时间是否超过三天
function isMoreThanThreeDaysAgo(dateStr) {
    const threeDaysAgo = new Date();
    threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);

    const date = new Date(dateStr);

    return date < threeDaysAgo;
}

var ctx = "/home/productBrowsing"
var cprefix = "/home/compare"
var opennc = "/home/opennc"
var path = "http://116.204.52.153:8012";
var http = "http://"
//var path = "http://127.0.0.1:8012";

function isPreview(params) {
    console.log(params);
    var arr = [".pdf", ".docx", ".ppt", ".pptx",".txt", ".xlsx", ".xls", ".png", ".jpg", ".doc", ".nc",".tar"];
    var fileId = params.split(",")[1];
    var fileName = params.split(",")[2];
    var filetime = params.split(",")[3];
    var filePath = params.split(",")[4];
    //如果不是nc文件直接在线预览
    console.log("如果不是nc文件直接在线预览")
        if ("-1" == arr.indexOf(getType(fileName))) {
            var result = params.split(",");
            $.ajax({
                url: ctx + "/isPreview",
                type: "post",
                async: true,
                data: {
                    "productId": result[0],
                },
                dataType: "json",
                success: function (data) {
                    console.log(data)
                    console.log("=========")
                    if (data.code == web_status.SUCCESS) {
                        window.location.href = ctx + "/toPreviews?productId=" + result[0] + "&id=" + result[1] +
                            "&fileName=" + result[2] + "&updateDate=" + result[3];
                    } else {
                        //doc、docx、ppt、pptx、xls、xlsx、txt、pdf
                        $.modal.alertWarning("仅支持 word、ppt、excel 等格式预览");
                    }
                }
            });
        } else {
            console.log(getType(fileName))
            if (getType(fileName) == ".nc") {
                console.log($("#qbsj").text())
                console.log($("#sjjg").text())
                console.log($("#cpsjlx").text())

                //var file = fileName + "$" + filetime + "$" + filePath + "$" +qbsx+ "$" +sjjg
                var prefix = "/leaflet/map";
                var qbsj = "no";//默认值
                var sjjg = "no";//默认值
                var cpsjlx = "no";//默认值
                var isjc = "no"//默认值
                if($("#qbsj").text()!=""){
                    //qbsj = $("#qbsj").text()
                    if($("#qbsj").text()=="世界时00时"){
                        qbsj = "01";
                    }
                    if($("#qbsj").text()=="世界时12时"){
                        qbsj = "02";
                    }
                    if($("#qbsj").text()=="世界时00/12时"){
                        qbsj = "03";
                    }
                    if($("#qbsj").text()=="世界时16时"){
                        qbsj = "04";
                    }
                }
                if($("#sjjg").text()!=""){
                    sjjg = $("#sjjg").text()
                }
                if($("#cpsjlx").text()){
                    cpsjlx = $("#cpsjlx").text()
                }
                if($("#isjc").text()!=""){
                    isjc = $("#isjc").text();
                }
                console.log($("#isjc").text()+"===================")
                console.log(qbsj+"qbsj")
                console.log(sjjg+"sjjg")
                var namep = $("#namep").text()
                console.log("参数："+fileName+ "=" +qbsj+ "=" +sjjg+ "=" +cpsjlx+ "=" +isjc+"/"+namep)
                $.modal.openOptions({
                    title: $("#namep").val(),
                    url: prefix + "/yl/" + fileName+ "/" +qbsj+ "/" +sjjg+ "/" +cpsjlx+ "/" +isjc+"/"+namep,
                    width: "1800",
                    height: "900",
                    showButtonPanel: false,
                    btn: ['关闭'],
                    yes: function (index, layero) {
                        $.modal.close(index);//使用layer.close(index);无效
                    },
                    cancel: function (index, layero) {
                        $.modal.close(index);
                    }
                });
            }else if(getType(fileName) == ".tar"){
                var prefix = "/leaflet/map";
                $.modal.openOptions({
                    title: '预览',
                    url: prefix + "/yltar/" + fileName,
                    width: "800",
                    height: "800",
                    showButtonPanel: false,
                    btn: ['关闭'],
                    yes: function (index, layero) {
                        $.modal.close(index);//使用layer.close(index);无效
                    },
                    cancel: function (index, layero) {
                        $.modal.close(index);
                    }
                });
            } else {//普通文件展示
                console.log(filetime.replace(/\s+/g, 'T'))
                var domain = window.location.host;
                var s = filePath + "/" + fileName;
                let hz = fileName.split(".")
                let strings = s.split("cloud");
                console.log(strings)
                console.log(http + domain + '/cloud' + strings[1])
                var url = http + domain + '/cloud' + strings[1]
                //window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
                console.log(isMoreThanThreeDaysAgo(filetime.replace(/\s+/g, 'T')));
                /* if(isMoreThanThreeDaysAgo(filetime.replace(/\s+/g, 'T'))){
                     $.modal.msgWarning("文件已超过三天不支持预览");
                 }else{*/
                /**
                 * 为了解决kkfileview插件因文件名过长无法预览问题进行解决 将文件通过后台把文件复制放到别的文件夹并修改名称返回给预览插件
                 */
                var prefix = "/leaflet/map";
                $.ajax({
                    url: prefix + "/upisview",
                    type: "post",
                    data: {
                        "filePath": s,
                        "path": filePath,
                        "hz": hz[1]
                    },
                    dataType: "json",
                    success: function (data) {
                        console.log(data.msg)
                        if(data.msg!=null) {
                        let strings = data.msg.split("cloud");
                        var url = http + domain + '/cloud' + strings[1]
                            console.log(url)
                            $.modal.openOptions({
                                title: '预览',
                                url: path + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)),
                                width: "1400",
                                height: "900",
                                showButtonPanel: false,
                                btn: ['关闭'],
                                yes: function (index, layero) {
                                    $.modal.close(index);//使用layer.close(index);无效
                                },
                                cancel: function (index, layero) {
                                    $.modal.close(index);
                                }
                            });
                        }else{
                            $.modal.alertWarning("未找到文件！")
                        }
                    }
                });
            }
        }

}

function isPreviewBackup(params) {
    var result = params.split(",");
    $.ajax({
        url: prefix + "/isPreview",
        type: "post",
        async: true,
        data: {
            "productId": result[0],
        },
        dataType: "json",
        success: function (data) {
            if (data.success) {
                window.location.href = prefix + "/toPreviews&productId=" + result[0] + "&id=" + result[1] +
                    "&fileName=" + result[2] + "&updateDate=" + result[3];
            } else {
                //doc、docx、ppt、pptx、xls、xlsx、txt、pdf
                alert("仅支持 word、ppt、txt、excel 等格式预览");
            }
        }
    });
}

function downLoad(fileId,path,pid) {
    var lj = '';
    if (!isLogin()) {
        showLoginDiv();
    } else {
        console.log(fileId)
        console.log(path)
        var p = path.split("_");
        var productId = $("#productId").val();
       // $.get(ctx + "/download?fileId=" + fileId + "&productId=" + productId)
        var hz = path.substring(path.length-2,path.length);
        if(hz === 'nc'){//判断下载是否为nc文件
            var prefix1 ="system/url";
            lj = "cloud/ocean/"+p[0]+"/"+p[1]+"/"+p[2]+"/"+p[3]+"/"+path;
            $.post('/system/order/tjwyxzsj', {path: lj,cp:pid}, function (res) {//将该下载单设置为网页端下载
                $.modal.openOptions({
                    title: '裁剪',
                    url: prefix1 + '/cjdata/' + fileId,
                    width: "900",
                    height: "900",
                    showButtonPanel: false,
                    btn: ['关闭'],
                    yes: function (index, layero) {
                        $.modal.close(index);//使用layer.close(index);无效
                    },
                    cancel: function (index, layero) {
                        $.modal.close(index);
                    }
                });
            })
        }else{
            var p = path.split("_");
            lj = "cloud/ocean/"+p[0]+"/"+p[1]+"/"+p[2]+"/"+p[3]+"/"+path;
            $.post('/system/order/tjwyxzsj', {path: lj,cp:pid}, function (res) {//将该下载单设置为网页端下载
                console.log(res)
                //window.location.href = ctx + "/download?fileId=" + fileId + "&productId=" + productId;
                var urlp =ctx + "/download?fileId=" + fileId + "&productId=" + productId
                // 创建一个隐藏的iframe元素
                var iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                // 设置iframe的src属性为文件的URL
                iframe.src = urlp; // 替换为实际的文件URL
                // 将iframe添加到页面中
                document.body.appendChild(iframe);
            })
        }
    }
}

function isLogin() {
    var loginName = "[[${@permission.getPrincipalPropertyUnLogged('loginName')}]]";
    if (loginName) {
        return true
    } else {
        return false
    }
}

function dateArrayTransfer(dateArray) {
    if (dateArray == null || dateArray == '') {
        return '';
    }
    console.log("时间")
    var returnDate;
    if(dateArray.length==6){
        returnDate = dateArray[0] + "-" +
            returnDoubleNum(dateArray[1]) + "-" +
            returnDoubleNum(dateArray[2]) + " " +
            returnDoubleNum(dateArray[3]) + ":" +
            returnDoubleNum(dateArray[4]) + ":" +
            returnDoubleNum(dateArray[5]);
    }else{
        returnDate = dateArray[0] + "-" +
            returnDoubleNum(dateArray[1]) + "-" +
            returnDoubleNum(dateArray[2]) + " " +
            returnDoubleNum(dateArray[3]) + ":" +
            returnDoubleNum(dateArray[4]) + ":" +
            "00"
    }

    return returnDate;
}

//保证两位数
function returnDoubleNum(number) {
    return (Array(2).join(0) + number).slice(-2);//创建一个长度为2的数组，且默认用0填充；然后用传过来的数添加都右边，然后从右向左截取两位！
}


function paraseDate(date) {
    if (date == undefined) {
        return "未知";
    }
    var y = date.year < 1900 ? 1900 + date.year : date.year;
    var m = date.month + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.date;
    d = d < 10 ? ('0' + d) : d;
    var h = date.hours;
    h = h < 10 ? ('0' + h) : h;
    var min = date.minutes;
    min = min < 10 ? ('0' + min) : min;
    var s = date.seconds;
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;
}

function toOrderDownLoad(fileId) {
    if (!isLogin()) {
        showLoginDiv();
    } else {
        $.ajax({
            type: "post",
            async: true,
            url: "introduce.do?transferToDownOrder",
            data: {
                "fileId": fileId
            },
            success: function (data) {
                var id = eval(data);
                if (id == '1') {
                    alert("已添加至下载器");
                } else if (id == '2') {
                    alert("该文件尚未下载完成，请下载完成后再添加");
                } else if (id == '3') {
                    alert("部门未下载文件达到上限，不能添加，请先下载未下载的文件再进行添加");
                } else {
                    alert("下载器添加文件失败");
                }
            }
        });
    }
}

function toSubscribe(productId) {
    if (productId != null && productId != "") {
        window.location.href = prefix + "/subscription/" + productId;
    }
}

function toUnzip(ncFileId) {
    if (ncFileId != null && ncFileId != "") {
        window.location.href = prefix + "/toUnzip?ncFileId=" + ncFileId;
    }
}

function toShowImage(ncFileId) {
    if (ncFileId != null && ncFileId != "") {
        window.location.href = prefix + "/toShowImage?imageProductId=" + ncFileId;
    }
}

//获取文件后缀
function getType(file) {
    var filename = file;
    var index1 = filename.lastIndexOf(".");
    var index2 = filename.length;
    var type = filename.substring(index1, index2);
    return type;
}
